import sys
import io
from PySide6.QtCore import QObject, Signal, Slot
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from system_status import SystemStatus
from dinosaur_breeding_process import AutoBreeding

import logging
# 设置日志级别为 INFO，这样 DEBUG 信息就不会输出
logging.getLogger('ppocr').setLevel(logging.INFO)

import logging
# 日志配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 默认调试账号和密码
DEBUG_USERNAME = "admin"
DEBUG_PASSWORD = "123456"


class OutputRedirector(QObject):
    textWritten = Signal(str)

    def __init__(self):
        super().__init__()
        self._buffer = io.StringIO()

    def write(self, text):
        if text:
            self._buffer.write(text)
            self.textWritten.emit(text)

    def flush(self):
        self._buffer.flush()

# 自定义日志处理器，将日志信息重定向到 OutputRedirector
class QmlLogHandler(logging.Handler):
    def __init__(self, output_redirector):
        super().__init__()
        self.output_redirector = output_redirector

    def emit(self, record):
        try:
            msg = self.format(record)
            self.output_redirector.write(msg + '\n')
        except Exception:
            self.handleError(record)

# 养龙信号
class BreedDinosaur(QObject):
    breedDinosaurSignal = Signal(str, str, str, str, str)

    @Slot(str, str, str, str, str)
    def breed_dinosaur(self, note, save_note, name, quantity, grade):
        # 实例化自动养龙类

        logger.warning("开始自动养龙 {} {} {} {} {}".format(note, save_note, name, quantity, grade))
        print(f"开始自动养龙: {note} {save_note} {name} {quantity} {grade}")
        AutoBreeding(note, save_note, name, int(quantity), grade)



if __name__ == "__main__":
    app = QGuiApplication(sys.argv)

    # 创建 QML 引擎
    engine = QQmlApplicationEngine()

    # 将 Python 变量暴露给 QML
    engine.rootContext().setContextProperty("DEBUG_USERNAME", DEBUG_USERNAME)
    engine.rootContext().setContextProperty("DEBUG_PASSWORD", DEBUG_PASSWORD)

    # 重定向标准输出
    output_redirector = OutputRedirector()
    sys.stdout = output_redirector

    engine.rootContext().setContextProperty("outputRedirector", output_redirector)

    # 添加自定义日志处理器
    qml_handler = QmlLogHandler(output_redirector)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    qml_handler.setFormatter(formatter)
    logging.getLogger().addHandler(qml_handler)


    # 实例化养龙信号
    breedDinosaur = BreedDinosaur()
    engine.rootContext().setContextProperty("breedDinosaur", breedDinosaur)

    # 实例化系统状态信号
    systemStatus = SystemStatus()
    engine.rootContext().setContextProperty("systemStatus", systemStatus)

    # 加载 QML 文件
    engine.load("qml/main.qml")

    # 获取根对象并连接信号到 QML 的 addLog 函数
    

    if not engine.rootObjects():
        sys.exit(-1)

    # 示例打印，会输出到 QML 日志区域
    print("程序已启动")

    sys.exit(app.exec())